package com.jfsnpm.jfsnpm.plugin.snakerflow;


import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snaker.engine.SnakerException;
import org.snaker.engine.helper.AssertHelper;
import org.snaker.engine.helper.ConfigHelper;
import org.snaker.engine.helper.StringHelper;
import org.snaker.engine.scheduling.IScheduler;
import org.snaker.engine.scheduling.JobEntity;
import org.snaker.engine.scheduling.quartz.ExecutorJob;
import org.snaker.engine.scheduling.quartz.ReminderJob;

import com.jfsnpm.jfsnpm.plugin.quartz.QuartzPlugin;

/**
* quartz框架实现的调度实例-修改getScheduler从插件获取，去除calendar。
* @author yuqs 天为之殇
*/
public class QuartzScheduler implements IScheduler {
	private static final Logger log = LoggerFactory.getLogger(QuartzScheduler.class);

	private Scheduler getScheduler() {
		try {
			Scheduler scheduler = QuartzPlugin.getScheduler();
			scheduler.start();
			return scheduler;
		} catch (SchedulerException e) {
			throw new SnakerException(e);
		}
	}
	
	/**
	 * 根据job实体调度具体的任务
	 */
	public void schedule(JobEntity entity) {
		AssertHelper.notNull(entity);
	    JobDataMap data = new JobDataMap(entity.getArgs());
	    data.put(KEY, entity.getId());
	    data.put(MODEL, entity.getModelName());
	    Class<? extends Job> jobClazz = null;
	    String jobId = "";
	    switch(entity.getJobType()) {
	    case 0:
	    	jobClazz = ExecutorJob.class;
	    	jobId = TYPE_EXECUTOR + entity.getTask().getId();
	    	break;
	    case 1:
	    	jobClazz = ReminderJob.class;
	    	jobId = TYPE_REMINDER + entity.getTask().getId();
	    	break;
	    }
	    if(jobClazz == null) {
	    	log.error("Quartz不支持的JOB类型:{}", entity.getJobType());
	    	return;
	    }
	    
	    JobDetail job = JobBuilder
	    		.newJob(jobClazz)
	    		.usingJobData(data)
	    		.withIdentity(jobId, GROUP)
	    		.build();
	    Trigger trigger = null;
	    TriggerBuilder<Trigger> builder = TriggerBuilder
	    		.newTrigger()
	    		.withIdentity(StringHelper.getPrimaryKey(), GROUP)
	    		.startAt(entity.getStartTime());
	    if(jobClazz == ReminderJob.class && entity.getPeriod() > 0) {
	    	int count = ConfigHelper.getNumerProperty(CONFIG_REPEAT);
	    	/*int count = 0;
	    	String[] reminderTime = StringUtils.split(entity.getTask().getModel().getReminderTime(),",");
	    	if(reminderTime.length == 2) count = Integer.parseInt(reminderTime[1]);*/
	    	if(count <= 0) count = 1;
	    	builder.withSchedule(SimpleScheduleBuilder.
   				repeatMinutelyForTotalCount(count, entity.getPeriod()));
	    }
	    trigger = builder.build();
	    try {
	    	log.info("jobId:{} class:{} starting......", jobId, jobClazz);
			getScheduler().scheduleJob(job, trigger);
		} catch (SchedulerException e) {
			log.error(e.getMessage());
		}
	}

	public void delete(String key) {
		AssertHelper.notEmpty(key);
		try {
			log.info("jobId:{} deleted......", key);
			getScheduler().deleteJob(new JobKey(key, GROUP));
		} catch (SchedulerException e) {
			log.error(e.getMessage());
		}
	}
}

